const multer = require("@koa/multer");
const fs = require('fs');
const mime = require('mime-types')


const filePath = './assets/template'

const fileUpload = multer({
	// multer调用diskStorage可控制磁盘存储引擎
	storage: multer.diskStorage({
		destination(req, file, cb) {
			//和启动路径相关
			cb(null, filePath)
		},
		// 文件名使用cb回调更改，参数二是文件名，为了保证命名不重复，使用时间戳
		filename(req, {originalname}, cb) {
			cb(null, originalname)
		}
	})
}).array('file')


const createMkdir = async (ctx,next) => {
	if (!fs.existsSync(filePath)){
		fs.mkdirSync(filePath,(err)=>{
			if (err) {
				console.log('创建失败')
			} else {
				console.log('临时目录创建成功')
			}
		})
	}
	await next()
}

const uploadAvatar = multer({
	storage: multer.diskStorage({
		destination(req, file, cb) {
			//和启动路径相关
			cb(null, './assets')
		},
		filename(req, file, cb) {
			req.url = file.originalname
			cb(null, file.originalname)
		}
	})
}).single('file')


const getFileName = async (ctx) => {
	if (!fs.existsSync(filePath)){
		fs.mkdirSync(filePath,(err)=>{
			if (err) {
				console.log('创建失败')
			} else {
				console.log('临时目录创建成功')
			}
		})
	}

	const fileList = fs.readdirSync(filePath)
	const finishChunk = fileList.map(filename => {
		return {
			filename,
			size:fs.statSync(`${filePath}/${filename}`).size
		}
	})

	ctx.body = {
		finishChunk,
		message:'获取成功'
	}
}

const mergeFiles = (ctx,next) => {
	const fileList = fs.readdirSync(filePath).sort((a,b)=>{
		const reg = /_(\d+)/;
		return reg.exec(a)[1] - reg.exec(b)[1];
	})
	const fileName = fileList.at(-1).split('.')
	fileList.forEach(item => {
		fs.appendFileSync(`./assets/${fileName.at(0)}.${fileName.at(-1)}`, fs.readFileSync(`${filePath}/${item}`));
		fs.unlinkSync(`${filePath}/${item}`);//删除切片文件
	})
	ctx.url = `${fileName.at(0)}.${fileName.at(-1)}`
	next()
}

const download = (ctx,next) => {
	const {filename} = ctx.query
	ctx.set({
		'Content-type':mime.lookup(filename),
		"Access-Control-Expose-Headers":"Content-Disposition",
		// 就是在请求的时候，就告诉浏览器，我的这次请求是要下载一个文件到本地，在请求头中添加：进一步指定文件名
		'Content-disposition':`attachment;filename=${encodeURI(filename)}`,
		'Content-length': fs.statSync(`./assets/${filename}`).size // 下载时文件大小
	})
	ctx.body = fs.createReadStream(`./assets/${filename}`)
}


const deleteFile = (ctx) => {
	const {filename} = ctx.query
	fs.unlinkSync(`assets/${filename}`);//删除切片文件
	ctx.body = {
		message:'删除成功',
		code:200
	}
}


const getFileList = (ctx) => {
	ctx.body = {
		fileList:fs.readdirSync('./assets').map(name => {
			console.log(name)
			return {
				size:fs.statSync(`./assets/${name}`).size,
				name
			}
		}),
		message:'获取成功'
	}
}

module.exports = {
	fileUpload,
	getFileName,
	createMkdir,
	mergeFiles,
	uploadAvatar,
	download,
	getFileList,
	deleteFile
}
